import { useState } from 'react'
import { MoreVertical, Play, Edit, Trash } from 'lucide-react'
import { Scene } from '@/types/scene'
import { 
  Activity as SceneIcon,
  Clock as ClockIcon,
  Bolt as BoltIcon,
  Settings as SettingsIcon
} from 'lucide-react'
import { Card } from '../ui/Card'
import toast from 'react-hot-toast'

interface SceneCardProps {
  scene: Scene
  onExecute: (id: string) => Promise<void>
  onDelete: (id: string) => Promise<void>
  onEdit: (scene: Scene) => void
}

export default function SceneCard({ scene, onExecute, onDelete, onEdit }: SceneCardProps) {
  const [loading, setLoading] = useState(false)
  const [executing, setExecuting] = useState(false)

  // 添加日志查看传入的数据
  console.log('Scene data in card:', scene)

  // 添加调试日志
  console.log('Scene full data:', {
    name: scene.name,
    devices: scene.devices,
    conditions: scene.conditions,
    actions: scene.actions
  })

  // 确保 conditions 和 actions 总是数组
  const conditions = scene.conditions || []
  const actions = scene.actions || []

  // 格式化条件显示
  const formatCondition = (condition: any) => {
    // 从 scene.devices 中查找设备
    const device = condition.deviceId ? scene.devices?.find(d => d.id === condition.deviceId) : null
    
    switch (condition.type) {
      case 'device':
        return `${device?.name || '未知设备'} ${condition.value?.state === 'on' ? '开启' : '关闭'}`
      case 'time':
        const timeValue = condition.value?.replace(/['"\\]/g, '')
        return `时间 ${timeValue}`
      case 'temperature':
        return `温度${condition.operator === '>' ? '大于' : 
               condition.operator === '<' ? '小于' :
               condition.operator === '>=' ? '大于等于' :
               condition.operator === '<=' ? '小于等于' : '等于'} ${condition.value}°C`
      case 'humidity':
        return `湿度${condition.operator === '>' ? '大于' : 
               condition.operator === '<' ? '小于' :
               condition.operator === '>=' ? '大于等于' :
               condition.operator === '<=' ? '小于等于' : '等于'} ${condition.value}%`
      case 'brightness':
        return `亮度${condition.operator === '>' ? '大于' : 
               condition.operator === '<' ? '小于' :
               condition.operator === '>=' ? '大于等于' :
               condition.operator === '<=' ? '小于等于' : '等于'} ${condition.value}`
      case 'motion':
        return `运动检测${condition.value ? '有' : '无'}`
      default:
        return `${condition.type} ${condition.operator} ${condition.value}`
    }
  }

  // 格式化动作显示
  const formatAction = (action: any) => {
    // 从 action 中直接获取设备ID
    const deviceId = action.deviceId
    const device = scene.devices?.find(d => d.id === deviceId)
    
    switch (action.type) {
      case 'switch':
        const value = action.value?.replace(/['"\\]/g, '') // 移除多余的引号
        return `${device?.name || '未知设备'} ${value === 'on' ? '开启' : '关闭'}`
      case 'brightness':
        return `${device?.name || '未知设备'} 亮度设为 ${action.value}%`
      case 'temperature':
        return `${device?.name || '未知设备'} 温度设为 ${action.value}°C`
      case 'color':
        return `${device?.name || '未知设备'} 颜色设为 ${action.value}`
      case 'curtain':
        return `${device?.name || '未知设备'} 开合度设为 ${action.value}%`
      default:
        return `${device?.name || '未知设备'} ${action.type} ${action.value}`
    }
  }

  const handleExecute = async (e: React.MouseEvent) => {
    e.stopPropagation()
    try {
      setExecuting(true)
      const response = await fetch(`/api/scenes/${scene.id}/execute`, {
        method: 'POST',
      })
      
      const data = await response.json()
      
      if (!response.ok) {
        throw new Error(data.error || '执行失败')
      }

      toast.success(data.message || `场景「${scene.name}」执行完成`)
    } catch (error: any) {
      toast.error(`场景「${scene.name}」执行失败`)
    } finally {
      setExecuting(false)
    }
  }

  const handleDelete = async (e: React.MouseEvent) => {
    e.stopPropagation()
    if (confirm('确定要删除这个场景吗？')) {
      try {
        setLoading(true)
        await onDelete(scene.id)
      } finally {
        setLoading(false)
      }
    }
  }

  const handleEdit = (e: React.MouseEvent) => {
    e.stopPropagation()
    onEdit(scene)
  }

  return (
    <div className="relative bg-white/5 rounded-lg p-4 hover:bg-white/10 transition-colors">
      <div className="flex items-start justify-between">
        <div>
          <h3 className="text-lg font-medium text-white/90">{scene.name}</h3>
          {scene.group && (
            <span className="text-sm text-white/50">
              分组: {scene.group.name}
            </span>
          )}
        </div>
        
        <div className="relative group">
          <button
            className="p-1 text-white/50 hover:text-white/90 transition-colors"
          >
            <MoreVertical className="w-5 h-5" />
          </button>

          <div className="hidden group-hover:block absolute right-0 top-8 w-32 py-1 bg-gray-800 rounded-lg shadow-lg border border-white/10 z-10">
            <button
              onClick={handleExecute}
              disabled={executing || loading}
              className="w-full px-3 py-2 text-left text-sm text-white/70 hover:bg-white/10 flex items-center space-x-2"
            >
              {executing ? (
                <>
                  <div className="w-4 h-4 border-2 border-white/20 border-t-white/90 rounded-full animate-spin" />
                  <span>执行中...</span>
                </>
              ) : (
                <>
                  <Play className="w-4 h-4" />
                  <span>立即执行</span>
                </>
              )}
            </button>
            <button
              onClick={handleEdit}
              disabled={loading}
              className="w-full px-3 py-2 text-left text-sm text-white/70 hover:bg-white/10 flex items-center space-x-2"
            >
              <Edit className="w-4 h-4" />
              <span>修改</span>
            </button>
            <button
              onClick={handleDelete}
              disabled={loading}
              className="w-full px-3 py-2 text-left text-sm text-red-400 hover:bg-white/10 flex items-center space-x-2"
            >
              <Trash className="w-4 h-4" />
              <span>删除</span>
            </button>
          </div>
        </div>
      </div>

      {/* 场景信息 */}
      <div className="mt-4 space-y-2">
        {conditions.length > 0 && (
          <div className="text-sm">
            <div className="text-white/50 mb-1">触发条件:</div>
            <ul className="list-disc list-inside pl-2 text-white/70">
              {conditions.map((condition, index) => (
                <li key={index}>{formatCondition(condition)}</li>
              ))}
            </ul>
          </div>
        )}
        
        {actions.length > 0 && (
          <div className="text-sm">
            <div className="text-white/50 mb-1">执行动作:</div>
            <ul className="list-disc list-inside pl-2 text-white/70">
              {actions.map((action, index) => (
                <li key={index}>{formatAction(action)}</li>
              ))}
            </ul>
          </div>
        )}
      </div>

      {/* 执行状态遮罩 */}
      {executing && (
        <div className="absolute inset-0 bg-black/20 rounded-lg flex items-center justify-center">
          <div className="bg-gray-800 rounded-lg px-4 py-2 flex items-center space-x-2">
            <div className="w-5 h-5 border-2 border-white/20 border-t-white/90 rounded-full animate-spin" />
            <span className="text-white/90">执行中...</span>
          </div>
        </div>
      )}

      {/* 原有的加载状态 */}
      {loading && (
        <div className="absolute inset-0 bg-black/20 rounded-lg flex items-center justify-center">
          <div className="w-6 h-6 border-2 border-white/20 border-t-white/90 rounded-full animate-spin" />
        </div>
      )}
    </div>
  )
} 